﻿using System;
using System.Collections.Generic;
using System.Linq;
using Model.Entity;
using Ones.Dal.Infrastructure;
using Ones.Dal.Repository.Interfaces;

namespace Ones.Dal.Repository.Impl
{
    public class JobDao : AbstractDao<Job>, IJobDao
    {
        public override bool
        create(Job job)
        {
            try
            {
                job.jobId = this.createPrefixId();

                _ctx.Jobs.InsertOnSubmit(job);
                _ctx.SubmitChanges();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public override bool
        update(Job job)
        {
            try
            {
                var curr = getById(job.jobId);

                curr.jobTitle = job.jobTitle;
                curr.jobDescription = job.jobDescription;

                _ctx.SubmitChanges();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public string
        createPrefixId()
        {
            string currMaxId = getAll().Max(i => i.jobId);
            string prefixPart = "job";
            int nDigits = 4;

            AutoId autoid = new AutoId();

            return autoid.tryCreatePrefixId(currMaxId, prefixPart, nDigits);
        }

        public override Job
        getById(object id)
        {
            return getSingle(i => i.jobId.Equals((string)id));
        }

        public List<Job>
        getByTitle(string jobTitle)
        {
            try
            {
                return getMultiple(i => i.jobTitle.Contains(jobTitle));
            }
            catch (Exception)
            {
                return null;
            }
        }

        public Job
        getByTitleExactly(string jobTitle)
        {
            return getSingle(i => i.jobTitle.Equals(jobTitle));
        }
    }

    #region IJobDao

    public interface IJobDao : IDao<Job>
    {
        String createPrefixId();

        List<Job> getByTitle(String jobTitle);

        Job getByTitleExactly(String jobTitle);
    }
    #endregion
}